import { animate, style, transition, trigger } from '@angular/animations';
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, Inject, PLATFORM_ID, Input, OnChanges, SimpleChanges, AfterViewInit, ChangeDetectorRef, OnDestroy, TemplateRef } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { ScrollEl, ScrollService } from '../../../services/tools/scroll.service';
 
@Component({
  selector: 'app-back-top',
  templateUrl: './back-top.component.html',
  styleUrls: ['./back-top.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('fadeShow', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('.2s', style({ opacity: 1 })),
      ]),
      transition(':leave', [
        animate('.2s', style({ opacity: 0 })),
      ]),
    ]),
  ],
})
export class BackTopComponent
  implements OnInit, OnChanges, AfterViewInit, OnDestroy
{
  @Input() target: string | HTMLElement;
  @Input() visibleHight = 450;
  @Input() tpl: TemplateRef<any>;

  private scrollTarget: HTMLElement;
  visible = false;
  scrollHandle: Subscription;
  constructor(
    @Inject(PLATFORM_ID) private platformId: object,
    @Inject(DOCUMENT) private doc: Document,
    private cdr: ChangeDetectorRef,
    private scrollService:ScrollService
  ) {
    console.log(this.getTarget());
  }

  ngOnInit(): void {}
  ngOnChanges(changes: SimpleChanges): void {
    const { target } = changes;
    if (target) {
      this.scrollTarget =
        typeof target.currentValue === 'string'
          ? this.doc.querySelector(target.currentValue)
          : target.currentValue;
    }
  }

  ngAfterViewInit(): void {
    if (isPlatformBrowser(this.platformId)) {
      this.listenScrollEvent();
    }
  }
  ngOnDestroy(): void {
    if (this.scrollHandle) {
      this.scrollHandle.unsubscribe();
    }
  }
  listenScrollEvent(): void {
    this.scrollHandle = fromEvent(this.getTarget(), 'scroll')
      .pipe(debounceTime(200))
      .subscribe(() => {
        const currentScrollValue = this.scrollService.getScroll(
          this.getTarget()
        );
        console.log(currentScrollValue);
        this.visible = currentScrollValue > this.visibleHight;
        this.cdr.markForCheck();
      });
  }
  private getTarget(): ScrollEl {
    return this.scrollTarget || window;
  }
  clickBack() {
    if (isPlatformBrowser(this.platformId)) {
      this.scrollService.scrollTop(this.getTarget());
    }
  } 
}
